package com.ljc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljc.common.lang.Result;
import com.ljc.entity.User;
import com.ljc.mapper.UserMapper;
import com.ljc.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljc.shiro.AccountProfile;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;

import java.util.Date;



/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author feiyu
 * @since 2021-11-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Result register(User user) {
        int count = this.count(new QueryWrapper<User>()
                .eq("email", user.getEmail())
                .eq("username", user.getUsername())
        );

        if (count > 0) {
            return Result.fail("用户名或者邮箱已被占用1");
        }
        User temp = new User();
        temp.setUsername(user.getUsername());
        temp.setPassword(SecureUtil.md5(user.getPassword()));
        temp.setEmail(user.getEmail());
        temp.setCreated(new Date());
        temp.setPoint(0);
        temp.setVipLevel(0);
        temp.setCommentCount(0);
        temp.setPostCount(0);
        temp.setGender("0");
        temp.setAvatar("/res/images/avatar/default.png");
        this.save(temp);
        return Result.success();
    }

    /**
     *   * 用户密码判断
     *@Author: ljc
     *@Date:Created in 9:34 2022/2/8

     */
    @Override
    public AccountProfile login(String email, String password) {
        User user = this.getOne(new QueryWrapper<User>().eq("email", email));
        if (user == null) {
            //用户名错误
            throw new UnknownAccountException();
        }
        if (!user.getPassword().equals(password)) {
            //密码错误
            throw new IncorrectCredentialsException();
        }
        user.setLasted(new Date());
        this.updateById(user);
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        return profile;
    }
}
